package handlers

import (
	"data_service/models"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// CreateInterestCircle 创建新兴趣圈
func CreateInterestCircle(c *gin.Context) {
	var circle models.InterestCircle
	if err := c.ShouldBindJSON(&circle); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的参数"})
		return
	}

	// 获取创建者ID（从token或上下文获取，这里简化处理）
	creatorID, _ := strconv.ParseUint(c.PostForm("creator_id"), 10, 32)
	circle.CreatorID = uint(creatorID)

	if err := models.CreateInterestCircle(&circle); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建兴趣圈失败"})
		return
	}

	// 自动将创建者添加为圈子成员
	//member := models.CircleMember{
	//	CircleID: circle.ID,
	//	UserID:   circle.CreatorID,
	//	Role:     "owner",
	//	Status:   "active",
	//	JoinDate: time.Now().Unix(),
	//}
	//这里应该有一个models.CreateCircleMember函数
	//if err := models.CreateCircleMember(&member); err != nil {
	//	c.JSON(http.StatusInternalServerError, gin.H{"error": "添加成员失败"})
	//	return
	//}

	c.JSON(http.StatusOK, circle)
}

// GetCircleByID 获取兴趣圈详情
func GetCircleByID(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的圈子ID"})
		return
	}

	circle, err := models.GetCircleByID(uint(id))
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "兴趣圈不存在"})
		return
	}

	c.JSON(http.StatusOK, circle)
}

// GetUserCircles 获取用户加入的所有圈子
func GetUserCircles(c *gin.Context) {
	userId, err := strconv.ParseUint(c.Param("user_id"), 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的用户ID"})
		return
	}

	circles, err := models.GetCirclesByUserID(uint(userId))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取圈子失败"})
		return
	}

	c.JSON(http.StatusOK, circles)
}
